package bam.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bam.dao.UserDao;
import bam.entity.Useraccount;
import bam.entity.Userinfo;
import bam.entity.Users;
import bam.util.DateUtil;
import bam.util.PagingUtil;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	public Users selUser(int uid) throws Exception {
		Users users = this.getHibernateTemplate().get(Users.class,uid);
		return users;
	}

	public List<Useraccount> selUseraccountList(int userid) throws Exception {
		Query query = this.getSession().createQuery("from Useraccount where users_id = ?");
		query.setParameter(0, userid);
		List <Useraccount>list = query.list();
		return list;
	}

	
	
	public void selUserList(PagingUtil<Useraccount> pu,
			String sousuo,Date firstlogin) throws Exception {
		if(sousuo==null)
			sousuo="";
		
		if(firstlogin==null){
			firstlogin = DateUtil.getparse("2015-01-01 00:00:00");
		}
		pu.setLogCount(slurcount(sousuo,firstlogin));
		String sql="SELECT ua.* FROM  useraccount AS ua ,users AS u WHERE ua.`users_id`= u.id " +
				"AND u.firstlogin>? " +
				"AND(ua.`account`LIKE ? " +
				"OR ua.`weixin_open`LIKE ? " +
				"OR u.nickname LIKE ? " +
				"OR u.niu_num LIKE ? )";
		Query query = this.getSession().createSQLQuery(sql).addEntity(Useraccount.class);
		query.setParameter(0, firstlogin);
		for (int i = 1; i < 5; i++) {
			query.setParameter(i, "%"+sousuo+"%");
		}
		int start=(pu.getPageNo()-1)*pu.getPageSize();
		int size = pu.getPageSize();
		query.setFirstResult(start);
		query.setMaxResults(size);
		List<Useraccount> list = query.list();
		pu.setList(list);
	}
	private int slurcount(String sousuo,Date firstlogin)throws Exception{
	
		String sql="SELECT count(ua.id) FROM  useraccount AS ua ,users AS u WHERE ua.`users_id`= u.id " +
				"AND u.firstlogin>? " +
				"AND(ua.`account`LIKE ? " +
				"OR ua.`weixin_open`LIKE ? " +
				"OR u.nickname LIKE ? " +
				"OR u.niu_num LIKE ? )";
		Query query = this.getSession().createSQLQuery(sql);
		query.setParameter(0, firstlogin);
		for (int i = 1; i < 5; i++) {
			query.setParameter(i, "%"+sousuo+"%");
		}
		Integer uniqueResult =Integer.parseInt(query.uniqueResult().toString());
		
		System.out.println("uniqueResult:"+uniqueResult);
		return uniqueResult;
	}
}
